<template>
  <div>
    <photo-view :list="list" @close="close" />
    <el-form label-width="130px" :model="form" ref="methodRef" :rules="rules">
      <div>
        <el-row style="margin-bottom: 5px">
          <el-col :span="22">
            <p class="pinformation">基本信息</p>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="方法编号：" prop="methodCode">{{
              form.methodCode || "/"
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="方法名称：" prop="methodName">
              <div v-html="proxy.getSupAndSub(form.methodName)" v-if="form.methodName"></div>
              <div v-else>/</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="方法简称：" prop="methodSimpleName">{{
              form.methodSimpleName || "/"
            }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="英文名称：" prop="methodEnglishName">{{
              form.methodEnglishName || "/"
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属标准：" prop="standardId">
              {{
                proxy.getItemByArray(
                  standardList,
                  "standardId",
                  form.standardId,
                  "standardCode"
                ) || "/"
              }}
              &nbsp;&nbsp;
              {{
                proxy.getItemByArray(
                  standardList,
                  "standardId",
                  form.standardId,
                  "standardName"
                )
              }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="使用场景：" prop="useTypeId">{{
              proxy.getItemByArray(
                scenario,
                "useTypeId",
                form.useTypeId + "",
                "useTypeName"
              ) || "/"
            }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="标准内排序号：">{{
              form.orderId || "/"
            }}</el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="适用范围截图：" :disabled="true">
          <span v-if="form.fileList.length" @click="list = form.fileList"
            style="color: var(--theme-deep-color);cursor: pointer;">{{ form.fileList[0].fileName }}</span>
          <span v-else>/</span>
        </el-form-item>
      </div>
    </el-form>
    <el-row>
      <p class="pinformation">适用范围</p>
      <p class="totalStyle">共 {{ form.handleJcxmList.length }} 条数据</p>
      <el-row style="padding-bottom: 5px; margin-left: 15px">
        <el-button link type="success" @click="isBatchYesClick('isUse', 'isAuth', 'isAgree')"
          :disabled="!isBatchYesList.length">本机构批量使用</el-button>
        <el-button link type="success" :disabled="!isBatchYesList.length"
          @click="isBatchYesClick('isAuth', 'isUse', 'isAgree')">计量认证批量通过</el-button>
        <el-button link type="success" :disabled="!isBatchYesList.length"
          @click="isBatchYesClick('isAgree', 'isUse', 'isAuth')">国家实验室认可批量通过</el-button>
      </el-row>
    </el-row>
    <el-table class="business" :data="form.handleJcxmList" ref="subTableRef" @selection-change="selectionChange"
      :row-key="dataId">
      <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
      <el-table-column label="序号" type="index" width="70" align="center" />
      <el-table-column label="前处理" align="center" width="130" prop="handle.handleMc" />
      <el-table-column label="检测类别" width="130" align="center" :show-overflow-tooltip="true">
        <template #default="scope">{{ scope.row.jclbNames }}</template>
      </el-table-column>
      <el-table-column width="150" label="检测项目" align="center" prop="jcxmId">
        <template #default="scope"><span v-html="transformation(getJcxmName(scope.row))"></span></template>
      </el-table-column>
      <el-table-column width="130" label="组别" align="center" prop="groupId">
        <template #default="scope">
          <dict-tag :options="lims_jcxm_group" :value="scope.row.groupId" />
        </template>
      </el-table-column>
      <el-table-column width="130" label="方法检出限" align="center" prop="checkLimit" />
      <el-table-column label="机构检出限" align="center" prop="orgCheckLimit" width="150" />
      <el-table-column label="机构检出限单位" align="center" prop="orgCheckLimitUnit" width="130">
        <template #default="scope"><span v-html="transformation(scope.row.orgCheckLimitUnit)"></span></template>
      </el-table-column>
      <el-table-column width="130" label="单位" align="center" prop="unitId">
        <template #default="scope"><span v-html="transformation(scope.row.unitName)"></span></template>
      </el-table-column>
      <el-table-column width="130" label="检测下限" align="center" prop="checkDownLimit" />
      <el-table-column width="130" label="检测上限" align="center" prop="checkUpLimit" />
      <el-table-column width="130" label="条件" align="center" :show-overflow-tooltip="true">
        <template #default="scope">
          <template v-if="scope.row.condition">当<span v-html="transformation(scope.row.condition)
            "></span>时</template>
        </template>
      </el-table-column>
      <el-table-column label="本机构是否使用" align="center" width="130">
        <template #default="scope">
          {{ scope.row.isUse ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="通过计量认证" align="center" width="130">
        <template #default="scope">
          {{ scope.row.isAuth ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="通过国家实验室认证" align="center" width="150">
        <template #default="scope">
          {{ scope.row.isAgree ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" type="index" fixed="right" width="105">
        <template #default="scope">
          <el-button link type="success" @click="subhandleAdd(scope.row, scope.$index)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :class="'el-dialog-theme3'" v-model="open" :title="title" width="1000" append-to-body
      @close="closedDialog" draggable :close-on-click-modal="false">
      <el-form label-width="118" :model="subForm" ref="subRef">
        <el-form-item label="前处理名称：">{{
          subForm.handleMc || "/"
        }}</el-form-item>
        <el-form-item label="检测类型：">{{
          subForm.jclbNames || "/"
        }}</el-form-item>
        <el-form-item label="条件：">
          <el-row v-if="subForm.condition">
            <span>
              当<span v-html="transformation(subForm.condition)"></span>时
            </span></el-row>
          <span v-if="!subForm.condition">/</span>
        </el-form-item>
      </el-form>
      <p class="pinformation">检测项目配置</p>
      <el-form label-width="118" :model="jcxmForm" ref="jcxmRef">
        <el-row>
          <el-col :span="5">
            <el-form-item label="组别：">
              <dict-tag :options="lims_jcxm_group" :value="jcxmForm.groupId" v-if="jcxmForm.groupId" />
              <span v-else>/</span>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="检测项目：" prop="jcxmId">
              <el-tooltip class="box-item" effect="customized" placement="top">
                <template #content>
                  <span v-html="transformation(getJcxmName(jcxmForm))"></span>
                </template>
                <div style="
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                  ">
                  <span v-html="transformation(getJcxmName(jcxmForm))"></span>
                </div>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="方法检出限：" prop="checkLimit">{{
              jcxmForm.checkLimit || "/"
            }}</el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="检出限单位：" prop="unitId">
              <span v-html="transformation(jcxmForm.unitName)" v-if="jcxmForm.unitName"></span>
              <span v-else>/</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="机构检出限：" prop="orgCheckLimit">
              <el-input v-model.trim="jcxmForm.orgCheckLimit" clearable oninput="value=value.replace(/[^0-9.]/g,'')"
                @blur="jcxmForm.orgCheckLimit = $event.target.value"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="机构检出限单位：" prop="orgCheckLimitUnit">
              <el-select v-model="jcxmForm.orgCheckLimitUnit" filterable clearable style="width: 100%;">
                <el-option v-for="item in unitList" :key="item.unitName" :label="item.unitName" :value="item.unitName">
                  <span v-html="transformation(item.unitName)"></span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="检测下限：">{{
              jcxmForm.checkDownLimit || "/"
            }}</el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="检测上限：">{{
              jcxmForm.checkUpLimit || "/"
            }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="本机构是否使用：">
              <el-select v-model="jcxmForm.isUse" clearable>
                <el-option v-for="item in isUseOrg" :key="item.authId" :value="item.authId"
                  :label="item.authName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计量认证：">
              <el-select v-model="jcxmForm.isAuth" clearable>
                <el-option v-for="item in metering" :key="item.authId" :value="item.authId"
                  :label="item.authName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="国家实验室认证：" label-width="140">
              <el-select v-model="jcxmForm.isAgree" clearable>
                <el-option v-for="item in metering" :key="item.authId" :value="item.authId"
                  :label="item.authName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-row justify="end">
              <el-button type="success" @click="save">确定</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <p class="pinformation">检测项目列表</p>
      <el-table class="business" height="15vw" max-height="20vw" :data="subTable">
        <el-table-column label="组别" align="center" prop="groupId" width="130">
          <template #default="scope">
            <dict-tag :options="lims_jcxm_group" :value="scope.row.groupId" />
          </template>
        </el-table-column>
        <el-table-column label="检测项目" align="center" prop="jcxmId" width="150">
          <template #default="scope"><span v-html="transformation(getJcxmName(scope.row))"></span></template>
        </el-table-column>
        <el-table-column label="方法检出限" align="center" prop="checkLimit" width="100" />
        <el-table-column label="单位" align="center" prop="unitName">
          <template #default="scope"><span v-html="transformation(scope.row.unitName)"></span></template>
        </el-table-column>
        <el-table-column label="检测下限" align="center" prop="checkDownLimit" />
        <el-table-column label="检测上限" align="center" prop="checkUpLimit" />
        <el-table-column label="机构检出限" align="center" prop="orgCheckLimit" width="100" />
        <el-table-column label="机构检出限单位" align="center" prop="orgCheckLimitUnit" width="130">
          <template #default="scope"><span v-html="transformation(scope.row.orgCheckLimitUnit)"></span></template>
        </el-table-column>
        <el-table-column label="本机构是否使用" align="center" width="130">
          <template #default="scope">
            {{ scope.row.isUse ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column label="通过计量认证" align="center" width="130">
          <template #default="scope">
            {{ scope.row.isAuth ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column label="通过国家实验室认证" align="center" width="150">
          <template #default="scope">
            {{ scope.row.isAgree ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" type="index" fixed="right" width="130">
          <template #default="scope">
            <el-button link type="success" @click="subEairt(scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="subSave">保 存</el-button>
          <el-button type="danger" @click="open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listAllJcxm } from "@/api/store/jcxm";
import { listStandard } from "@/api/store/standard";
import { getUnitList } from "@/api/store/unit";
import { addMethod, getMethod } from "@/api/store/method";
import useMethodStore from "@/store/modules/method";
import { jcffPut } from "@/api/store/jcffConfig";
import { onMounted } from "vue";

// 接收父组件传递过来的数据或方法
const props = defineProps({
  // 获取检测方法列表
  getDetectionMethod: {
    type: Function,
  },
  handleQuery: {
    type: Function,
  },
  queryParams: {
    type: Object,
  },
});

const { proxy } = getCurrentInstance();
const methodStore = useMethodStore();
const MethodForm = computed(() => methodStore.MethodForm);

const { lims_jcxm_group } = proxy.useShareDict("lims_jcxm_group");

const standardList = ref([]);
const jcxmList = ref([]);
const unitList = ref([]);
const open = ref(false);
const title = ref("");

//使用场景
const scenario = ref([
  { useTypeId: 0, useTypeName: "实验室分析方法" },
  { useTypeId: 1, useTypeName: "采样方法" },
]);
// 计量认证
const metering = ref([
  { authId: 0, authName: "未通过" },
  { authId: 1, authName: "已通过" },
]);
// 机构
const isUseOrg = ref([
  { authId: 0, authName: "否" },
  { authId: 1, authName: "是" },
]);

const charact = ref([
  { characterName: "=", characterId: 0 },
  { characterName: ">", characterId: 1 },
  { characterName: "<", characterId: 2 },
  { characterName: "≥", characterId: 3 },
  { characterName: "≤", characterId: 4 },
]);
const subTable = ref([]);
const andForm = ref([
  { andName: "或", andId: 0 },
  { andName: "且", andId: 1 },
]);

const conditionForm = ref({});
const data = reactive({
  form: { handleJcxmList: [], fileList: [] },
  subForm: {},
  jcxmForm: {},
  rules: {
    isAuth: [{ required: true, message: "计量认证不能为空", trigger: "blur" }],
    isUse: [
      { required: true, message: "本机构是否使用不能为空", trigger: "blur" },
    ],
    isAgree: [
      { required: true, message: "国家实验室认证不能为空", trigger: "blur" },
    ],
  },
});

const { form, subForm, jcxmForm, rules } = toRefs(data);

watch(MethodForm, () => {
  form.value = MethodForm.value;
  form.value.handleJcxmList.forEach((item) => {
    if (!item.isAuth) item.isAuth = 0;
    if (!item.isAgree) item.isAgree = 0;
    if (!item.isUse) item.isUse = 0;
  });
});

listStandard().then((res) => {
  standardList.value = res.data;
});

listAllJcxm().then((res) => {
  jcxmList.value = res.data;
});


//新增或编辑适用范围
function subhandleAdd(row, index) {
  listAllJcxm().then((res) => {
    jcxmList.value = res.data;
  });
  getUnitList().then((res) => {
    unitList.value = res.data;
  });
  open.value = true;
  title.value = "修改适用范围";
  let formData = JSON.parse(JSON.stringify(row));
  subForm.value = formData.handle;
  subForm.value.jclbNames = formData.jclbNames
  subForm.value.condition = formData.condition
  subForm.value.index = index;
  subTable.value = [formData];
}

function getJcxmName(row) {
  return proxy.getItemByArray(jcxmList.value, "jcxmId", row.jcxmId, "jcxmName");
}

function subEairt(row) {
  jcxmForm.value = JSON.parse(JSON.stringify(row));
}

const heightParams = ref([{ tableName: "sub", bottomHeight: 21 }]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}


onMounted(() => {
  nextTick(function () {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  });
});

onUpdated(() => {
  nextTick(function () {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

function closedDialog() {
  subForm.value = {};
  subTable.value = [];
  jcxmForm.value = {};
  conditionForm.value = {};
  unitList.value = [];
  proxy.$refs["subRef"].clearValidate();
}

const emits = defineEmits(["isDisable"]);

/** 提交按钮 */
function submitForm() {
  var tempJcxmList = [];
  form.value.handleJcxmList.forEach((item) => {
    tempJcxmList.push({
      orgCheckLimit: item.orgCheckLimit,
      orgCheckLimitUnit: item.orgCheckLimitUnit,
      handleJcxmId: item.handleJcxmId,
      jcxmId: item.jcxmId,
      isAuth: item.isAuth,
      isAgree: item.isAgree,
      isUse: item.isUse,
      methodId: form.value.methodId,
    });
  });
  let temp = {
    status: form.value.status,
    methodId: form.value.methodId,
    handleJcxmList: tempJcxmList,
  };
  addMethod(temp).then((res) => {
    proxy.$modal.msgSuccess("编辑成功");
    props.getDetectionMethod();
  });
}

//将检测项目信息放到检测项目列表中。
function save() {
  proxy.$refs["jcxmRef"].validate((valid) => {
    if (valid) {
      if (jcxmForm.value.handleJcxmId) {
        subTable.value.forEach((item, index) => {
          if (item.handleJcxmId == jcxmForm.value.handleJcxmId) {
            subTable.value[index] = JSON.parse(JSON.stringify(jcxmForm.value));
            clearJcxmForm();
          }
        });
      } else {
        proxy.$modal.msgError("未选择要修改的检测项目");
      }
    }
  });
}

function clearJcxmForm() {
  delete jcxmForm.value.handleJcxmId;
  delete jcxmForm.value.jcxmId;
  delete jcxmForm.value.orgCheckLimit;
  delete jcxmForm.value.orgCheckLimitUnit;
  delete jcxmForm.value.orgFlow;
  delete jcxmForm.value.orgFlowUnit;
  delete jcxmForm.value.orgTimeLength;
  delete jcxmForm.value.orgTimeUnit;
  delete jcxmForm.value.isAuth;
  delete jcxmForm.value.isAgree;
  delete jcxmForm.value.isUse;
}

//将检测项目列表放到适用范围列表中。
function subSave() {
  proxy.$refs["subRef"].validate((valid) => {
    if (valid) {
      form.value.handleJcxmList[subForm.value.index] = subTable.value[0]
      submitForm();
      open.value = false;
    }
  });
}

const isBatchYesList = ref([]);
function selectionChange(selection) {
  isBatchYesList.value = selection;
}

function isBatchYesClick(name, delName1, delName2) {
  let temp = JSON.parse(JSON.stringify(isBatchYesList.value));
  temp.forEach((item) => {
    eval("item." + name + "=1");
    eval("delete item." + delName1);
    eval("delete item." + delName2);
  });
  jcffPut(temp).then((res) => {
    proxy.$modal.msgSuccess("保存成功");
    getMethod(form.value.methodId).then((response) => {
      form.value = response.data;
    });
  });
}

function dataId(row) {
  return row.handleJcxmId;
}

function transformation(row) {
  const a = proxy.getSupAndSub(row);
  return a;
}

function reset() {
  proxy.resetForm("methodRef");
}

defineExpose({
  reset
})

const list = ref([])
function close() {
  list.value = []
}
</script>
